

<template>

    <basic-container>

      <el-aside  style="position: absolute" width="200px">
        <avue-tree :option="treeOption" :data="treeDeptData" @node-click="nodeClick"></avue-tree>
      </el-aside>
      <el-main style="margin-left: 220px">
      <avue-crud :option="option"
                 ref="crud"
                 v-model="form"
                 :page="page"
                 :table-loading="listLoading"
                 :permission="permissionList"
                 :data="list"
                 @on-load="getList"
                 @size-change="sizeChange"
                 @current-change="currentChange"
                 @row-del="rowDel"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @refresh-change="refreshChange"
                 @selection-change="selectionChange"
                 :before-open="beforeOpen"
                 >
        <template slot="menuLeft">
          <el-button type="danger"
                     size="small"
                     icon="el-icon-delete"
                     plain
                     v-if="permissions.sys_user_del"
                     @click="handleDelete">删 除
          </el-button>
          <el-button type="primary"
                     size="small"
                     plain
                     v-if="permissions.sys_user_reset"
                     icon="el-icon-refresh"
                     @click="handleReset">密码重置
          </el-button>
          <el-button type="success"
                     size="small"
                     plain
                     v-if="permissions.sys_user_import"
                     icon="el-icon-upload2"
                     @click="handleImport">导入
          </el-button>
          <el-button type="warning"
                     size="small"
                     plain
                     v-if="permissions.sys_user_export"
                     icon="el-icon-download"
                     @click="handleExport">导出
          </el-button>
        </template>
        <template slot="role"
                  slot-scope="scope">
              <span v-for="(role,index) in scope.row.roleList"
                    :key="index">
                <el-tag>{{role.roleName}} </el-tag>
              </span>
        </template>

        <template slot="deptId"
                  slot-scope="scope">
          <el-tag>{{scope.row.deptName}}</el-tag>
        </template>
        <template slot="lockFlag"
                  slot-scope="scope">
          <el-tag>{{scope.label}}</el-tag>
        </template>
      </avue-crud>

      <el-dialog title="用户数据导入"
                 append-to-body
                 :visible.sync="excelBox"
                 width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate()">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
      </el-main>

    </basic-container>


</template>

<script>
  import {addObj, delObj, fetchList, putObj,resetPassword} from "@/api/admin/user";
  import {fetchRoleList} from "@/api/admin/role";
  import {fetchDeptList, fetchTree} from "@/api/admin/dept";
  import {tableOption} from '@/const/crud/admin/user';
  import {getToken} from '@/util/auth';
  import {serialize} from '@/util/util'
  import {mapGetters} from "vuex";

  export default {
    name: "table_user",
    data() {
      return {
        option: tableOption,
        treeDeptData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10, // 每页显示多少条
        },
        list: [],
        selectionList: [],
        listLoading: true,
        role: [],
        searchForm: {},
        form: {},
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/admin/user/import"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },
        treeOption:{
          defaultExpandAll:false,
          menu:false,
          addBtn:false,
          props:{
            labelText:'标题',
            label:'name',
            value:'id',
            children:'children'
          }
        }
      };
    },
    computed: {
      ...mapGetters(["permissions"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions["sys_user_add"], false),
          delBtn: this.vaildData(this.permissions["sys_user_del"], false),
          editBtn: this.vaildData(this.permissions["sys_user_edit"], false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    created () {
      fetchTree().then(response => {
        this.treeDeptData = response.data.data;
        const column = this.findObject(this.option.column, "deptId");
        column.dicData = response.data.data;
      });
    },
    watch: {
      role() {
        this.form.role = this.role
      },
      'form.tenantId'() {
        if (this.form.tenantId !== '' && this.form.tenantId !== null
                && this.form.tenantId !== undefined) {
          fetchDeptList(this.form.tenantId).then(response => {
            const column = this.findObject(this.option.column, "deptId");
            column.dicData = response.data.data;
          });
          fetchRoleList(this.form.tenantId).then(response => {
            const column = this.findObject(this.option.column, "role");
            column.dicData = response.data.data;
          })
        }
      },
    },
    methods: {
      getList(page, params) {
        this.listLoading = true;
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.list = response.data.data.records;
          this.page.total = response.data.data.total
          this.listLoading = false;
        });
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      currentChange(current) {
        this.page.currentPage = current
      },
      searchChange(param, done) {
        this.searchForm = param;
        this.page.currentPage = 1
        this.getList(this.page, param);
        done()
      },

      searchReset() {
        this.searchForm = {};
        this.getList(this.page);
      },

      refreshChange() {
        this.getList(this.page,this.searchForm)
      },

      selectionChange(list) {
        this.selectionList = list;
      },

      beforeOpen(show, type) {
        window.boxType = type
        // 若是编辑、查看回显角色名称
        if (['edit', 'views'].includes(type)) {
          this.role = []
          for (let i = 0; i < this.form.roleList.length; i++) {
            this.role[i] = this.form.roleList[i].id;
          }
        } else if (type === 'add') {
          // 若是添加角色列表设置为空
          this.role = []
        }
        show();
      },

      rowSave(row, done, loading) {
        this.form.deptId = row.deptId;
        this.form.role = row.role;
        addObj(this.form).then(() => {
          this.getList(this.page);
          done();
          this.$notify.success('创建成功')
        }).catch(() => {
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        this.form.deptId = row.deptId;
        this.form.role = row.role;
        putObj(this.form).then(() => {
          this.getList(this.page);
          done();
          this.$notify.success('修改成功')
        }).catch(() => {
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消", type: "warning"
          }
        ).then(() => {
          delObj(row.id).then(() => {
            this.getList(this.page);
            this.$notify.success('删除成功')
          }).catch(() => {
            this.$notify.error('删除失败')
          });
        });
      },

      handleReset() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择账号密码重置为123456?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return resetPassword(this.ids);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },

      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return delObj(this.ids);
          })
          .then(() => {
            this.getList(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },


      handleImport() {
        this.excelBox = true;
      },
      handleExport() {
        this.$confirm("是否导出用户数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          const searchForm = serialize(this.$refs.crud.searchForm);
          window.open(`/admin/user/export?access_token=${getToken()}&${searchForm}`);
        });
      },
      handleTemplate() {
        window.open(`/admin/user/import/template?access_token=${getToken()}`);
      },
      uploadAfter(res, done) {
        done();
        this.excelBox = false;
        this.refreshChange();
        this.$message.success(res)
      },

      nodeClick(data){
        this.searchForm.deptId = data.id;
        this.getList(this.page);
      }
    }
  };
</script>
